package com.crystal.jcms.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import com.crystal.jcms.shpz.R;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;

public class UpdateManager {
	private Context mContext;
	String url = "http://172.16.88.1:83";
	String UPDATE_SERVERAPK = "Crystal.Jcms.Shpz.apk";
	String downPath = ""; // 下载包地址
	String newVerName = "";// 新版本名称
	int newVerCode = -1;// 新版本号 (服务器端的)
	// 用于发送handler事件的标志
	private static final int DOWNLOAD = 1;
	private static final int DOWNLOAD_FINISH = 2;
	private static final int NOTICE = 3;
	// 进度条的值
	private int progress;
	// 取消更新
	private boolean cancelUpdate = false;
	private ProgressBar mProgress;
	// 下载对话框
	private Dialog mDownloadDialog;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWNLOAD:
				mProgress.setProgress(progress);
				break;
			case DOWNLOAD_FINISH:
				update();
				break;
			case NOTICE:
				updateVersion();
				break;
			default:
				break;
			}
		}
	};

	public UpdateManager(Context context) {
		this.mContext = context;
		url = (String) SpUtils.get(mContext, "ServerUrl", "");
		downPath = url + "/Shpz/Download/" + UPDATE_SERVERAPK;
	}

	public void CheckUpdateInfo() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				if (GetServerVer()) {
					mHandler.sendEmptyMessage(NOTICE);
				}
			}
		}).start();
	}

	public void updateVersion() {
		if (Integer.toString(newVerCode) != "") {
			int verCode = this.getVerCode(mContext);
			if (newVerCode > verCode) {
				showNoticeDialog();
			}
		}
	}

	/**
	 * 获得本地版本号
	 */
	public int getVerCode(Context context) {
		int verCode = -1;
		try {
			String packName = context.getPackageName();
			verCode = context.getPackageManager().getPackageInfo(packName, 0).versionCode;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			Log.e("版本号获取异常", e.getMessage());
		}
		return verCode;
	}

	/**
	 * 获得本地版本名称
	 */
	public String getVerName(Context context) {
		String verName = "";
		try {
			String packName = context.getPackageName();
			verName = context.getPackageManager().getPackageInfo(packName, 0).versionName;
		} catch (NameNotFoundException e) {
			Log.e("版本名称获取异常", e.getMessage());
		}
		return verName;
	}

	public boolean GetServerVer() {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url;
			URL realUrl = new URL(urlNameString);
			HttpURLConnection httpConn = (HttpURLConnection) realUrl.openConnection();
			httpConn.setDoInput(true);
			httpConn.connect();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			JSONArray array = new JSONArray(result);
			JSONObject jsonObj = array.getJSONObject(0);
			String code = jsonObj.getString("verCode");
			newVerCode = Integer.parseInt(code);
			// downPath = jsonObj.getString("verPath");
			// newVerName = jsonObj.getString("verName");

		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
			return true;
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return true;
	}

	/**
	 * 从服务器端获得版本号与安装包路径
	 * 
	 */
	Runnable runnable = new Runnable() {
		public void run() {
			String result = "";
			BufferedReader in = null;
			try {
				String urlNameString = url;
				URL realUrl = new URL(urlNameString);
				HttpURLConnection httpConn = (HttpURLConnection) realUrl.openConnection();
				httpConn.setDoInput(true);
				httpConn.connect();
				// 定义 BufferedReader输入流来读取URL的响应
				in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
				String line;
				while ((line = in.readLine()) != null) {
					result += line;
				}
				JSONArray array = new JSONArray(result);
				JSONObject jsonObj = array.getJSONObject(0);
				String code = jsonObj.getString("verCode");
				newVerCode = Integer.parseInt(code);
				// downPath = jsonObj.getString("verPath");
				// newVerName = jsonObj.getString("verName");
			} catch (Exception e) {
				System.out.println("发送GET请求出现异常！" + e);
				e.printStackTrace();
			}
			// 使用finally块来关闭输入流
			finally {
				try {
					if (in != null) {
						in.close();
					}
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
	};

	/**
	 * 显示更新的提示对话框
	 */
	private void showNoticeDialog() {
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle("软件更新");
		builder.setCancelable(false);
		builder.setMessage("检测到新版本，立即更新吗");
		builder.setPositiveButton("更新", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				showDownloadDialog();
			}
		});

		builder.setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		try {
			Dialog noticeDialog = builder.create();
			noticeDialog.show();
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	/**
	 * 显示下载对话框
	 */
	private void showDownloadDialog() {
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle("正在更新");
		builder.setCancelable(false);
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.softupdate_progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
		builder.setView(v);
		builder.setNegativeButton("取消更新", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				cancelUpdate = true;
			}
		});
		mDownloadDialog = builder.create();
		mDownloadDialog.show();
		downFile(downPath);
	}

	/**
	 * 下载apk
	 */
	public void downFile(final String url) {
		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					long length = entity.getContentLength();
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						File file = new File(Environment.getExternalStorageDirectory(), UPDATE_SERVERAPK);
						fileOutputStream = new FileOutputStream(file);
						byte[] b = new byte[1024];
						int count = 0;
						do {
							int numread = is.read(b);
							count += numread;
							progress = (int) (((float) count / length) * 100);
							mHandler.sendEmptyMessage(DOWNLOAD);
							if (numread <= 0) {

								mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
								break;
							}
							fileOutputStream.write(b, 0, numread);
						} while (!cancelUpdate);
						fileOutputStream.flush();
						if (fileOutputStream != null) {
							fileOutputStream.close();
						}
						if (cancelUpdate) {
							file.delete();
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
	}

	/**
	 * 安装应用
	 */
	public void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), UPDATE_SERVERAPK)),
				"application/vnd.android.package-archive");
		mContext.startActivity(intent);
	}

}
